import React from "react";
import { useNavigate, Navigate, useLocation } from "react-router-dom";
// import userStore from "@/store/user";
import router from "./index";
import dayjs from "dayjs";
import { message } from "antd";

// dlu
const loginPath = router.filter((item) => item.name == "Login")[0].path;
const indexPath = "/";

// 路由表白名单
const allowList = ["/login"];

// 判断用户信息是否存在
const isUserInfo = (userInfo) => {
  return userInfo != null && userInfo != undefined && userInfo != ""
    ? true
    : false;
};

// 计算登录时间和现在相差多长时间  分钟
const calculateLoginCurrentDiffer = (loginTime, currentTime) => {
  return currentTime.diff(loginTime) / 1000 / 60;
};

// 权限路由 Hook
const AuthRoute = (props) => {
  // children 为子组件
  const { children } = props;

  // location 将要去到的路由
  const location = useLocation();

  // 登录路由
  const loginRoute = <Navigate to={loginPath} />;

  // 返回路由
  let returnRute = children;

  // 用户信息
  const userInfo = JSON.parse(localStorage.getItem("userInfo"));

  // 登录时间和现在时间差
  const loginTimeDiffer = calculateLoginCurrentDiffer(
    dayjs(JSON.parse(localStorage.getItem("loginTime"))),
    dayjs()
  );

  console.log("userInfo", userInfo);
  console.log("location", location);
  console.log("props", props);

  // 判断去到的路由是否在白名单内
  if (allowList.indexOf(location.pathname) != -1) {
    returnRute = children;
  } else {
    // 判断用户信息是否存在

    returnRute = children;

    console.log("登录时长", loginTimeDiffer);
    // 判断登录是否过期
    if (loginTimeDiffer >= 120) {
      message.error("登录已过期，请重新登录!");
      returnRute = loginRoute;
      // userStore.clearLoginInfo;
    }
  }

  return returnRute;
};
export default AuthRoute;
